//===============================================================================
// Microsoft patterns & practices
// Smart Client Software Factory
//===============================================================================
// Copyright (C) Microsoft Corporation.  All rights reserved.
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
// FITNESS FOR A PARTICULAR PURPOSE.
//===============================================================================
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
//===============================================================================

//----------------------------------------------------------------------------------------
// patterns & practices - Smart Client Software Factory - Guidance Package
//
// This file was generated by the "Add View" recipe.
//
// A presenter calls methods of a view to update the information that the view displays. 
// The view exposes its methods through an interface definition, and the presenter contains
// a reference to the view interface. This allows you to test the presenter with different 
// implementations of a view (for example, a mock view).
//
// For more information see:
// ms-help://MS.VSCC.v90/MS.VSIPCC.v90/ms.practices.scsf.2008apr/SCSF/html/02-09-010-ModelViewPresenter_MVP.htm
//
// Latest version of this Guidance Package: http://go.microsoft.com/fwlink/?LinkId=62182
//----------------------------------------------------------------------------------------

using System;
using Microsoft.Practices.ObjectBuilder;
using Microsoft.Practices.CompositeUI;
using QuickStart.Infrastructure.Interface;
using Microsoft.Practices.CompositeUI.EventBroker;
using QuickStart.RestaurantModule.Constants;
using QuickStart.RestaurantModule.RestaurantService;
using QuickStart.RestaurantModule.DSA.MenuServiceClient;
using QuickStart.RestaurantModule.Properties;
using Microsoft.Practices.SmartClient.DisconnectedAgent;

namespace QuickStart.RestaurantModule
{
    public partial class MenuItemsViewPresenter : Presenter<IMenuItemsView>
    {
        [EventPublication(EventTopicNames.StatusUpdate, PublicationScope.Global)]
        public event EventHandler<EventArgs<string>> StatusUpdate;

        [EventPublication(EventTopicNames.LongProcess, PublicationScope.WorkItem)]
        public event EventHandler<EventArgs> LongProcess;

		Agent _restaurantService;
        IConnectionMonitor _connectionMonitor;
        Restaurant _restaurant;

        public MenuItemsViewPresenter
            (
				[ServiceDependency] Agent restaurantService,
                [ServiceDependency] IConnectionMonitor connectionMonitor
            )
        {
            _connectionMonitor = connectionMonitor;
            _restaurantService = restaurantService;
            
            // Subscribe to the service agent callback events
			Callback.GetMenuItemsReturn += new EventHandler<EventArgs<MenuItem[]>>(GetMenuItemsReturn);
			Callback.GetMenuItemsException += new EventHandler<EventArgs<Exception>>(GetMenuItemsException);
        }

        /// <summary>
        /// Close the view
        /// </summary>
        public void OnCloseView()
        {
            base.CloseView();
        }

        [EventSubscription(EventTopicNames.RestaurantSelected, ThreadOption.UserInterface)]
        public void OnRestaurantSelected(object sender, EventArgs<Restaurant> eventArgs)
        {
            _restaurant = eventArgs.Data;
            TryGetMenuItems();
        }

        /// <summary>
        /// Tries to get the menu items. If the application is offline, it won't enqueue
        /// a request, it will update the view to display an offline message.
        /// If the application is online, it will enqueue the request.
        /// </summary>
        public void TryGetMenuItems()
        {
            if (Connected)
            {
                OnLongProcess(true);
                OnStatusUpdate(Resources.RetrievingMenuItems);
                _restaurantService.GetMenuItems(_restaurant.Identifier);
            }
            else
            {
                // If the application is not online, update the view to show an offline message
                View.ShowOfflineMessage();
            }
        }

        /// <summary>
        /// This method will be called when the service agent gets a
        /// successful response from the GetMenuItems method.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">GetMenuItems return value</param>
        private void GetMenuItemsReturn(object sender, EventArgs<MenuItem[]> e)
        {
            OnLongProcess(false);
            OnStatusUpdate(Resources.MenuItemsRecieved);
            View.ShowMenuItems(_restaurant.Name, e.Data);
        }

        /// <summary>
        /// This method will be called when the service agent gets an
        /// exception when calling the GetMenuItems method.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e">Exception thrown</param>
        private void GetMenuItemsException(object sender, EventArgs<Exception> e)
        {
            OnLongProcess(false);
            if (Connected)
            {
                OnStatusUpdate(Resources.ErrorRetrievingMenuItems);
                View.ShowConnectionError();
            }
            else
            {
                View.ShowOfflineMessage();
            }
        }

        private void OnStatusUpdate(string message)
        {
            if (StatusUpdate != null)
            {
                StatusUpdate(this, new EventArgs<string>(message));
            }
        }

        private void OnLongProcess(bool running)
        {
            if (LongProcess != null)
            {
                LongProcess(this, new EventArgs<bool>(running));
            }
        }

        private bool Connected
        {
            get { return _connectionMonitor.IsConnected; }
        }
    }
}